﻿using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using zijian666.SuperConvert;

namespace zijian666.WebApi.JsonOption
{
    /// <summary>
    /// 自定义JSON转换器
    /// </summary>
    static class JsonConverters
    {
        public static JsonConverter DateTime { get; } = new JsonFormatConverter<DateTime>("yyyy-MM-dd HH:mm:ss");
        public static JsonConverter DateTimeOffse { get; } = new JsonFormatConverter<DateTimeOffset>("yyyy-MM-dd HH:mm:ss");
        public static JsonConverter Timespan { get; } = new JsonFormatConverter<TimeSpan>(@"hh\:mm\:ss");

        private class JsonFormatConverter<T> : JsonConverter<T>
            where T : IFormattable
        {
            private readonly string _format;

            public JsonFormatConverter(string format) => _format = format ?? throw new ArgumentNullException(nameof(format));
            public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                var value = JsonSerializer.Deserialize<string>(ref reader, options);
                return value.To<T>();
            }

            public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
            {
                var result = value.ToString(_format, null);
                writer.WriteStringValue(result);
            }
        }
    }
}
